using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace SpriteEffectSystem.Editor
{
    [CustomEditor(typeof(SpriteEffectAnima))]
    public class SpriteEffectAnimaEditor : UnityEditor.Editor
    {
        private int _previewFrame = 1;
        private bool _playing = false;
        private Material _material;
        private double _playStartTime = 0;

        public override VisualElement CreateInspectorGUI()
        {
            _material = new Material(Shader.Find("Sprites/Default"));
            
            return base.CreateInspectorGUI();
        }

        private void OnEnable()
        {
            EditorApplication.update += Update;
        }

        private void OnDisable()
        {
            EditorApplication.update -= Update;
        }

        public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
        {
            var anima = (SpriteEffectAnima)target;
            var br = r;
            br.width = 60;
            br.height = 20;
            DrawPlayButton(br);
            var sr = r;
            sr.x += 65;
            sr.width -= 65;
            sr.height = 20;
            _previewFrame = EditorGUI.IntSlider(sr,_previewFrame, 1, anima.Frames.Length);
            var sprite = anima.Frames[_previewFrame - 1];
            r.y += 20;
            r.height -= 20;
            EditorGUI.DrawPreviewTexture(r, sprite.texture, _material, ScaleMode.ScaleToFit);
        }

        private void DrawPlayButton(Rect r)
        {
            var text = _playing ? "Replay" : "Play";
            var click = GUI.Button(r,text);
            
            if (click)
            {
                _previewFrame = 1;
                _playing = true;
                _playStartTime = EditorApplication.timeSinceStartup;
            }
        }

        public override GUIContent GetPreviewTitle()
        {
            return new GUIContent("动画预览");
        }

        public override bool HasPreviewGUI() => true;
        
        private void Update()
        {
            if (!_playing) return;
            
            var anima = (SpriteEffectAnima)target;
            var time = EditorApplication.timeSinceStartup - _playStartTime;
            _previewFrame = (int)(time * anima.Fps);
            if (anima.Fps == 0) _playing = false;
            if (_previewFrame >= anima.Frames.Length) _playing = false;
            
            Repaint();
        }
    }
}